<template>
	<view>
		<!--pages/scanDevices/scanDevices.wxml-->

		<view class="page-list-header">
			<h2>设备列表</h2>
		</view>
		<view class="page-body">
			<!-- <button bindtap="scanDeviceList">开始扫描</button>
  <button bindtap="stopScanDeviceList">结束扫描</button> -->
			<view class="log">
				<view>日志(可滑动查看)：</view>
				<view>
					<scroll-view scroll-y="true" class="text-box scroll-list">
						<text>{{textLog}}</text>
					</scroll-view>
				</view>
			</view>
			<view class="scan-view">
				<button class="btn" @tap="clearLogs">清空log日志</button>
			</view>
			<view class="devices-summary">发现 {{devices.length}} 个相关设备：</view>
			<scroll-view class="device-list" scroll-y scroll-with-animation>
				<view v-for="(item, index) in devices" :key="index" :data-device-id="item.deviceId"
					:data-name="item.name || item.localName" @tap="createBLEConnection" class="device-item"
					hover-class="device-item-hover">
					<view style="font-size: 16px; color: #333;">{{item.name}}</view>
					<view style="font-size: 10px">信号强度: {{item.RSSI}}dBm ({{utils.max(0, item.RSSI + 100)}}%)</view>
					<view style="font-size: 10px">UUID: {{item.deviceId}}</view>
					<view style="font-size: 10px">MAC地址: {{item.macAddr}}</view>
					<view style="font-size: 10px">Service数量: {{utils.len(item.advertisServiceUUIDs)}}</view>
					<view class="fr" style="position:absolute;top:30rpx;right: 20rpx">
						<text>连接设备</text>
						<icon class="ico-arrow-right" style="position:relative;top:4rpx"></icon>
					</view>
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script module="utils" lang="wxs" src="./utils.wxs"></script>

<script>
	var app = getApp();
	var utils = require("../../utils/util.js");

	export default {
		data() {
			return {
				isBlueToothOpen: false,
				textLog: "",
				devices: [],
				connected: false,
				currentDeviceType: ""
			};
		},

		components: {},
		props: {},

		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad: function(options) {
			var that = this;
			this.setData({
				currentDeviceType: options.deviceType,
				isBlueToothOpen: false,
				connected: false,
				devices: [],
				textLog: ""
			});
			console.log('ff')
			that.startScan();
		},

		/**
		 * 生命周期函数--监听页面初次渲染完成
		 */
		onReady: function() {},
		onShow: function() {},
		onUnload: function() {
			this.stopBluetoothDevicesDiscovery();
		},
		methods: {
			startScan: function() {
				var that = this;
				that._discoveryStarted = false;
				console.log('that.isBlueToothOpen', that.isBlueToothOpen)
				if (that.isBlueToothOpen) {
					// 如果已初始化小程序蓝牙模块，则直接执行扫描
					that.getBluetoothAdapterState();
				} else {
					that.openBluetoothAdapter();
				}
			},
			// 初始化小程序蓝牙模块
			openBluetoothAdapter: function() {
				var that = this;
				uni.openBluetoothAdapter({
					success: function(res) {
						uni.showToast({
							title: '打开蓝牙适配器成功！',
							icon: 'none',
							duration: 1500
						});
						var log = that.textLog + "打开蓝牙适配器成功！\n";
						that.setData({
							textLog: log,
							isBlueToothOpen: true
						});
						that.getBluetoothAdapterState();
					},
					fail: function(err) {
						var log = that.textLog + "蓝牙开关未开启 \n";
						that.setData({
							textLog: log,
							isBlueToothOpen: false
						});
						uni.showModal({
							title: '提示',
							content: "蓝牙开关未开启",
							showCancel: false
						});
					}
				}); // 监听蓝牙适配器状态变化事件

				uni.onBluetoothAdapterStateChange(function(res) {
					var isDvailable = res.available; //蓝牙适配器是否可用

					if (isDvailable) {
						that.getBluetoothAdapterState();
					} else {
						that.stopBluetoothDevicesDiscovery(); //停止搜索

						that.setData({
							devices: []
						});
						that.setData({
							isBlueToothOpen: false
						});
						uni.showModal({
							title: '提示',
							content: "蓝牙开关未开启",
							showCancel: false
						});
					}
				});
			},
			// 获取本机蓝牙适配器状态
			getBluetoothAdapterState: function() {
				var that = this;
				uni.getBluetoothAdapterState({
					success: function(res) {
						console.log(res)
						var isDiscov = res.discovering; // 是否正在搜索设备

						var isDvailable = res.available; // 蓝牙适配器是否可用

						if (isDvailable) {
							var log = that.textLog + "本机蓝牙适配器状态：可用 \n";
							that.setData({
								textLog: log
							});

							if (true) {
								that.startBluetoothDevicesDiscovery();
							} else {
								var log = that.textLog + "已在搜索设备 \n";
								that.setData({
									textLog: log
								});
							}
						}
					}
				});
			},
			// 开始扫描附近的蓝牙外围设备。
			// 注意，该操作比较耗费系统资源，请在搜索并连接到设备后调用 stop 方法停止搜索。
			startBluetoothDevicesDiscovery: function() {
				var that = this;

				if (that._discoveryStarted) {
					return;
				}

				that._discoveryStarted = true;
				uni.showLoading({
					title: "正在扫描..",
					mask: true
				});
				var log = that.textLog + "正在扫描..\n";
				that.setData({
					textLog: log
				});
				setTimeout(function() {
					uni.hideLoading(); // 隐藏loading
				}, 3000);
				uni.startBluetoothDevicesDiscovery({
					services: [],
					allowDuplicatesKey: true,
					// 是否允许重复上报同一设备, 如果允许重复上报，则onDeviceFound 方法会多次上报同一设备，但是 RSSI(信号) 值会有不同
					success: function(res) {
						var log = that.textLog + "扫描附近的蓝牙外围设备成功，准备监听寻找新设备:" + JSON.stringify(res) + "\n";
						that.setData({
							textLog: log
						});
						that.onBluetoothDeviceFound(); // 监听寻找到新设备的事件
					}
				});
			},
			// 停止搜寻附近的蓝牙外围设备。若已经找到需要的蓝牙设备并不需要继续搜索时，建议调用该接口停止蓝牙搜索。
			stopBluetoothDevicesDiscovery: function() {
				var that = this;
				var log = that.textLog + "停止搜寻附近的蓝牙外围设备 \n";
				that.setData({
					textLog: log
				});
				uni.stopBluetoothDevicesDiscovery();
			},
			// 监听寻找到新设备的事件
			onBluetoothDeviceFound: function() {
				var that = this;
				uni.onBluetoothDeviceFound(function(res) {
					res.devices.forEach(function(device) {
						if (!device.name && !device.localName) {
							return;
						}

						var macAddrStr = utils.ab2hex(device.advertisData).toUpperCase().replace(
							/(.{2})/g, '$1:');
						device.macAddr = macAddrStr.substring(macAddrStr.length - 18, macAddrStr
							.length - 1);
						const foundDevices = that.devices;
						const idx = utils.inArray(foundDevices, 'deviceId', device.deviceId);
						const data = {};

						if (idx === -1) {
							data[`devices[${foundDevices.length}]`] = device;
						} else {
							data[`devices[${idx}]`] = device;
						}

						that.setData(data);
					});
				});
			},
			// 连接低功耗蓝牙设备。
			createBLEConnection: function(e) {
				var ds = e.currentTarget.dataset;
				app.globalData.bindDeviceList.push({
					deviceType: this.currentDeviceType,
					deviceUUId: ds.deviceId,
					deviceName: ds.name
				});
				uni.navigateTo({
					url: '/pages/selectDevice/startpage'
				});
			},
			clearLogs: function() {
				this.setData({
					textLog: ""
				});
			},
			// 退出页面
			backPage: function() {
				uni.navigateBack({
					delta: -1
				});
			}
		}
	};
</script>
<style>
	/* pages/scanDevices/scanDevices.wxss */
	.log {
		width: 90%;
		left: 5%;
		position: relative;
		margin-top: 10rpx;
	}

	.scroll-list {
		max-height: 300rpx;
	}

	.scan-view {
		width: 100%;
		margin-top: 30rpx;
		display: flex;
		flex-direction: row;
		justify-content: space-between
	}

	.scan-view button {
		position: relative;
		display: block;
		margin-left: auto;
		margin-right: auto;
		padding-left: 28rpx;
		padding-right: 28rpx;
		box-sizing: border-box;
		font-size: 36rpx;
		width: 48%;
	}

	.devices-summary {
		margin-top: 60rpx;
		padding: 20rpx 5%;
		font-size: 32rpx;
	}

	.device-list {
		height: 400rpx;
		margin: 100rpx 5%;
		margin-top: 0;
		border: 2rpx solid #eee;
		border-radius: 10rpx;
		width: auto;
	}

	.device-item {
		border-bottom: 2rpx solid #eee;
		padding: 20rpx;
		color: #666;
		position: relative;
	}

	.device-item-hover {
		background-color: rgba(0, 0, 0, .1);
	}
</style>
